﻿using DataProcesss.model;
using OfficeOpenXml;
using OfficeOpenXml.Drawing;
using OfficeOpenXml.Style;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Common;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Windows;
using static OfficeOpenXml.ExcelErrorValue;
using NLog;
using OxyPlot.Axes;
using OxyPlot.Series;
using OxyPlot;

namespace DataProcesss
{
    public class RealtimeData
    {
        NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
        private BinaryWriter writer;
        private FileStream fileStream;

        public void OpenFile(string fileName)
        {
            try
            {
                fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);

                writer = new BinaryWriter(fileStream);
            }
            catch (Exception ex)
            {
                logger.Info("文件打开或创建失败: " + ex.Message);
            }
        }

        public void DataSave(Data data)
        {
            if (fileStream != null && writer != null)
            {
                try
                {
                    long currentPosition = fileStream.Length;
                    //Console.WriteLine(currentPosition);
                    long remainder = currentPosition % 156; // 140 字节是完整数据块的大小

                    if (remainder != 0)
                    {
                        fileStream.Seek(-remainder, SeekOrigin.End);
                        //Console.WriteLine("HUIS");
                    }
                    else
                    {
                        fileStream.Seek(0, SeekOrigin.End);
                    }

                    writer.Write(data.Time);
                    writer.Write(data.FurnaceCoverTemperature);
                    writer.Write(data.FurnaceTubeTemperature1);
                    writer.Write(data.FurnaceTubeTemperature2);
                    writer.Write(data.EvaporationTemperature1);
                    writer.Write(data.EvaporationTemperature2);
                    writer.Write(data.EvaporationTemperature3);
                    writer.Write(data.CrackingTemperature1);
                    writer.Write(data.CrackingTemperature2);
                    writer.Write(data.CrackingTemperature3);
                    writer.Write(data.AuxiliaryHeatingTemperature);
                    writer.Write(data.FreezingTemperature);
                    writer.Write(data.SilowallTemperature);
                    writer.Write(data.CouplingTemperature);
                    writer.Write(data.BinPressure);
                    writer.Write(data.PumpPressure);
                    writer.Write(data.Bak1Temp);
                    writer.Write(data.Bak2Temp);
                    writer.Flush();
                }
                catch (Exception ex)
                {
                    logger.Info("写入数据失败: " + ex.Message);
                }
            }
        }

        public void CloseFile()
        {
            try
            {
                if (writer != null)
                {
                    writer.Close();
                    writer = null;
                }
                if (fileStream != null)
                {
                    fileStream.Close();
                    fileStream = null;
                }
            }
            catch(Exception ex)
            {
                logger.Info("文件关闭失败: " + ex.Message);
            }
        }
        ////实时数据二进制保存
        ////private BinaryWriter writer;
        ////FileStream destStream;
        //private FileStream fileStream;
        //public void OpenFile(string fileName)
        //{
        //    //try
        //    //{
        //    //    //string absolutePath = Path.GetFullPath(fileName);
        //    //    //Console.WriteLine($"文件已打开或创建: {absolutePath}");
        //    //    //using (var stream = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
        //    //    //{
        //    //    //    stream.Close();
        //    //    //}
        //    //    writer = new BinaryWriter(File.Open(fileName, FileMode.Append));
        //    //}
        //    //catch (Exception ex)
        //    //{
        //    //    //Console.WriteLine($"文件打开或创建失败: {ex.Message}");
        //    //    logger.Info("文件打开或创建失败" + ex.ToString());
        //    //    writer = null;
        //    //}

        //    //writer = new BinaryWriter(File.Open(fileName, FileMode.Append));
        //    //destStream = new FileStream(fileName, FileMode.Append);

        //    fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);


        //}
        //public void DataSave(Data data)
        //{
        //    if (fileStream != null)
        //    {
        //        try
        //        {
        //            long currentPosition = fileStream.Position;
        //            long remainder = currentPosition % 139;//139为15个double一个string字节长度
        //            if (remainder != 0)
        //            {

        //                fileStream.Seek( - remainder, SeekOrigin.Current);
        //            }
        //            BinaryWriter writer = new BinaryWriter(fileStream);
        //            writer.Write(data.Time);
        //            writer.Write(data.FurnaceCoverTemperature);
        //            writer.Write(data.FurnaceTubeTemperature1);
        //            writer.Write(data.FurnaceTubeTemperature2);
        //            writer.Write(data.EvaporationTemperature1);
        //            writer.Write(data.EvaporationTemperature2);
        //            writer.Write(data.EvaporationTemperature3);
        //            writer.Write(data.CrackingTemperature1);
        //            writer.Write(data.CrackingTemperature2);
        //            writer.Write(data.CrackingTemperature3);
        //            writer.Write(data.AuxiliaryHeatingTemperature);
        //            writer.Write(data.FreezingTemperature);
        //            writer.Write(data.SilowallTemperature);
        //            writer.Write(data.CouplingTemperature);
        //            writer.Write(data.BinPressure);
        //            writer.Write(data.PumpPressure);
        //            writer.Flush();
        //        }
        //        catch (Exception ex)
        //        {
        //            //Debug.WriteLine($"写入数据失败: {ex.Message}");
        //            logger.Info("写入数据失败" + ex.ToString());
        //            //Console.WriteLine($"写入数据失败: {ex.Message}");
        //        }
        //    }
        //}
        //public void CloseFile()
        //{

        //    if (fileStream != null)
        //    {
        //        fileStream.Close();
        //        fileStream = null;
        //        //Console.WriteLine("文件关闭成功");
        //    }

        //    //if (writer != null)
        //    //{
        //    //    writer.Close();
        //    //    writer = null;
        //    //    //Console.WriteLine("文件关闭成功");
        //    //}
        //    //try
        //    //{
        //    //    if (destStream != null)
        //    //    {
        //    //        destStream.Close();
        //    //        destStream = null;
        //    //    }
        //    //}
        //    //catch(Exception ex) {
        //    //    logger.Info($"关闭文件发生错误: {ex.Message}");
        //    //}
        //}
        ////根据时间段获取数据
        public ObservableCollection<Data> DataSelect(ObservableCollection<Data> datas, string startTime = null, string endTime = null)
        {
            DateTime StartTimeToCheck;
            DateTime EndTimeToCheck;
            if (startTime == null && endTime == null)
            {
                StartTimeToCheck = DateTime.MinValue;
                EndTimeToCheck = DateTime.MaxValue;
            }
            else
            {
                string format = "yyyy-MM-dd HH:mm:ss";
                StartTimeToCheck = DateTime.ParseExact(startTime, format, null);
                EndTimeToCheck = DateTime.ParseExact(endTime, format, null);
            }
            var dataSource = new ObservableCollection<Data>();
            for (int i = 0;i< datas.Count; i++)
            {
                string time = datas[i].Time;
                if (DateTime.Parse(time) >= StartTimeToCheck && DateTime.Parse(time) <= EndTimeToCheck)
                {
                    dataSource.Add(datas[i]);
                }
            }
            return dataSource;
        }
        public ObservableCollection<Data> GetData(string fileName)
        {
            var dataSource = new ObservableCollection<Data>();
            if (!File.Exists(fileName))
            {
                return dataSource;
            }
            using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open)))
            {
                try
                {
                    while (reader.BaseStream.Position != reader.BaseStream.Length && (reader.BaseStream.Length - reader.BaseStream.Position) >= 156)//125为每次写入的14条数据占据字节长度
                    {
                        string value = reader.ReadString();
                        Data data = new Data();
                        data.Time = value;

                        for (int i = 0; i < 17; i++)
                        {
                            switch (i)
                            {
                                case 0:
                                    data.FurnaceCoverTemperature = reader.ReadDouble();
                                    break;
                                case 1:
                                    data.FurnaceTubeTemperature1 = reader.ReadDouble();
                                    break;
                                case 2:
                                    data.FurnaceTubeTemperature2 = reader.ReadDouble();
                                    break;
                                case 3:
                                    data.EvaporationTemperature1 = reader.ReadDouble();
                                    break;
                                case 4:
                                    data.EvaporationTemperature2 = reader.ReadDouble();
                                    break;
                                case 5:
                                    data.EvaporationTemperature3 = reader.ReadDouble();
                                    break;
                                case 6:
                                    data.CrackingTemperature1 = reader.ReadDouble();
                                    break;
                                case 7:
                                    data.CrackingTemperature2 = reader.ReadDouble();
                                    break;
                                case 8:
                                    data.CrackingTemperature3 = reader.ReadDouble();
                                    break;
                                case 9:
                                    data.AuxiliaryHeatingTemperature = reader.ReadDouble();
                                    break;
                                case 10:
                                    data.FreezingTemperature = reader.ReadDouble();
                                    break;
                                case 11:
                                    data.SilowallTemperature = reader.ReadDouble();
                                    break;
                                case 12:
                                    data.CouplingTemperature = reader.ReadDouble();
                                    break;
                                case 13:
                                    data.BinPressure = reader.ReadDouble();
                                    break;
                                case 14:
                                    data.PumpPressure = reader.ReadDouble();
                                    break;
                                case 15:
                                    data.Bak1Temp = reader.ReadDouble();
                                    break;
                                case 16:
                                    data.Bak2Temp = reader.ReadDouble();
                                    break;
                            }
                        }
                        dataSource.Add(data);
                    }
                }
                catch(Exception ex)
                {
                    logger.Info("数据读取失败: " + ex.Message);
                }
            }

            return dataSource;
        }


        public ObservableCollection<Data> GetData1(string fileName)
        {
            var dataSource = new ObservableCollection<Data>();
            if (!File.Exists(fileName))
            {
                return dataSource;
            }
            List<double> temp = new List<double>();

            using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open)))
            {
                try
                {
                    Console.WriteLine(reader.BaseStream.Length);
                    while (reader.BaseStream.Position != reader.BaseStream.Length)
                    {
                        //Console.WriteLine("-----------");

                        temp.Clear();
                        long startPosition = reader.BaseStream.Position;
                        double value = reader.ReadDouble();
                        long startPosition2 = reader.BaseStream.Position;
                        
                        if(startPosition2 - startPosition != 8)
                        {
                            Console.WriteLine("不等于8");
                        }
                        //while (temp.Count < 15 && reader.BaseStream.Position != reader.BaseStream.Length)
                        //{
                        //    long posBeforeRead = reader.BaseStream.Position;
                        //    try
                        //    {
                        //        double v = reader.ReadDouble();
                        //        long posAfterRead = reader.BaseStream.Position;

                        //        if ((posAfterRead - posBeforeRead) == 8) // 检查是否成功读取了一个 double
                        //        {
                        //            temp.Add(v);
                        //        }
                        //        else
                        //        {
                        //            reader.BaseStream.Position = posBeforeRead;
                        //            break; // 读取失败，跳出循环
                        //        }
                        //    }
                        //    catch (Exception)
                        //    {
                        //        // 如果读取 double 时出错，将流位置回退到字符串之后的位置

                        //        break;
                        //    }
                        //}

                        //if (temp.Count == 15)
                        //{
                        //    Data data = new Data
                        //    {
                        //        Time = value,
                        //        FurnaceCoverTemperature = temp[0],
                        //        FurnaceTubeTemperature1 = temp[1],
                        //        FurnaceTubeTemperature2 = temp[2],
                        //        EvaporationTemperature1 = temp[3],
                        //        EvaporationTemperature2 = temp[4],
                        //        EvaporationTemperature3 = temp[5],
                        //        CrackingTemperature1 = temp[6],
                        //        CrackingTemperature2 = temp[7],
                        //        CrackingTemperature3 = temp[8],
                        //        AuxiliaryHeatingTemperature = temp[9],
                        //        FreezingTemperature = temp[10],
                        //        SilowallTemperature = temp[11],
                        //        CouplingTemperature = temp[12],
                        //        BinPressure = temp[13],
                        //        PumpPressure = temp[14]
                        //    };
                        //    dataSource.Add(data); // 如果数据完整，将其加入集合
                        //}
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("读取文件时发生错误: " + ex.Message);
                }
            }

            return dataSource;
        }

    }

    //public class Exp
    //{
    //    static void Main()
    //    {
    //        RealtimeData datasave = new RealtimeData();
    //        DateTime currentDate = DateTime.Now;

    //        // 工令单号、设备号和镀膜开始时间
    //        string workOrderNumber = "工令单号";
    //        string equipmentNumber = "设备号";
    //        string coatingStartTime = currentDate.ToString("HHmmss");

    //        // 生成文件名
    //        string fileName = $"{workOrderNumber}_{equipmentNumber}_{currentDate.ToString("yyyyMMdd")}_{coatingStartTime}.csv";

    //        datasave.OpenFile("../../../data/工令单号_设备号_20240306_20240306_160313.dat");
    //        DateTime startTime = DateTime.Now;
    //        for (int i = 0; i < 300; i++)
    //        {
    //            startTime = startTime.AddMinutes(1);
    //            Data data1 = new Data
    //            {

    //                Time = startTime.ToString(),
    //                FurnaceCoverTemperature = i,
    //                FurnaceTubeTemperature1 = i + 1,
    //                FurnaceTubeTemperature2 = i + 1,
    //                EvaporationTemperature1 = i + 1,
    //                EvaporationTemperature2 = i + 2,
    //                EvaporationTemperature3 = i + 3,
    //                CrackingTemperature1 = i + 4,
    //                CrackingTemperature2 = i + 5,
    //                CrackingTemperature3 = i + 6,
    //                AuxiliaryHeatingTemperature = i + 7,
    //                FreezingTemperature = i + 8,
    //                SilowallTemperature = i + 9,
    //                BinPressure = i + 10,
    //                PumpPressure = i + 11,
    //            };
    //            datasave.DataSave(data1);
    //            datasave.CloseFile();
    //            ObservableCollection<Data> datas = new ObservableCollection<Data>();
    //            datas = datasave.GetData("../../../工令单号_设备号_1.dat");
    //        }

    //RealtimeData datasave = new RealtimeData();
    //datasave.OpenFile("C:\\Users\\lmtong\\Desktop\\kf\\11\\data\\_设备号_20240822_152558.dat");
    //        DateTime startTime = DateTime.Now;
    //        for (int i = 0; i< 300; i++)
    //        {
    //            startTime = startTime.AddMinutes(1);
    //            Data data1 = new Data
    //            {

    //                Time = startTime.ToString("yyyy/MM/dd HH:mm:ss"),
    //                FurnaceCoverTemperature = i,
    //                FurnaceTubeTemperature1 = i + 1,
    //                FurnaceTubeTemperature2 = i + 1,
    //                EvaporationTemperature1 = i + 1,
    //                EvaporationTemperature2 = i + 2,
    //                EvaporationTemperature3 = i + 3,
    //                CrackingTemperature1 = i + 4,
    //                CrackingTemperature2 = i + 5,
    //                CrackingTemperature3 = i + 6,
    //                AuxiliaryHeatingTemperature = i + 7,
    //                FreezingTemperature = i + 8,
    //                SilowallTemperature = i + 9,
    //                BinPressure = i + 10,
    //                PumpPressure = i + 11,
    //                CouplingTemperature = i + 12,
    //                Bak1Temp = 1,
    //                Bak2Temp = 2,
    //            };
    //datasave.DataSave(data1);
    //            Console.WriteLine(i);
    //        }

    //Data data = new Data
    //{

    //    Time = startTime.ToString("yyyy/M/dd HH:mm:ss"),
    //    FurnaceCoverTemperature = 0,
    //    FurnaceTubeTemperature1 = 1,
    //    FurnaceTubeTemperature2 = 1,
    //    EvaporationTemperature1 = 1,
    //    EvaporationTemperature2 = 2,
    //    EvaporationTemperature3 = 3,
    //    CrackingTemperature1 = 4,
    //    CrackingTemperature2 = 5,
    //    CrackingTemperature3 = 6,
    //    AuxiliaryHeatingTemperature = 7,
    //    FreezingTemperature = 8,
    //    SilowallTemperature = 9,
    //    BinPressure = 10,
    //    PumpPressure = 11,
    //    CouplingTemperature = 12,
    //    Bak1Temp = 1,
    //    Bak2Temp = 2,
    //};
    //datasave.DataSave(data);
    //datasave.CloseFile();

    //    }


    //}

}
